package com.markhsiu.store.disk;

import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel.MapMode;

import com.markhsiu.store.StoreDB;

/**
 * 多线程读
 * 
 * @author Mark Hsiu
 */
class MapFileRead extends MapFile {

	private MappedByteBuffer master;

	public MapFileRead(File file) {
		super(file);
		
		try {
			master = channel.map(MapMode.READ_ONLY, headLen(), size());
		} catch (IOException e) {
			e.printStackTrace();
		} 
		
	}
	
	public ByteBuffer duplicate(){
		return master.duplicate();
	}
	
	public int  readBlockM(ByteBuffer readUsed, byte[] output) {
	 
		readUsed.get(output, 0, CACHE_HEAD);
		if(output[0] != StoreDB.MAGIC){
			return 0;
		}
		short len = MessageUtil.byteToShort(output, 1);
		readUsed.get(output , CACHE_HEAD, len);
		return len; 
	}


	public void flush() throws IOException {
		// 不force的话，内存产生大量的垃圾page file
		channel.force(false);
	}

}
